defmodule TimerCycle do
	@moduledoc """
	    该模块做一些不重要的操作,比如说给用户推送一些通知,红点等消息
	"""

	import ErrCode, [:server_starting]
	require Logger
	alias Pango.SwarmUtil
	@max_cycle 10
	@cycle_time 1000
	def apply_cycle(m, f, a, num \\ 1) do
		case num <= @max_cycle && apply(m, f, a) do
			{:ok, _} ->
				:ok
			:ok ->
				:ok
			false ->
				Logger.error(inspect{m, f, a, " max apply_cycle time"})
				:ok
			err ->
				Logger.error(inspect(err))
				:timer.apply_after(
					@cycle_time,
					__MODULE__,
					:apply_cycle,
					[m, f, a, num + 1]
				)
		end
	end

	@rpc_cycle_time 3000
	def sync_call(service, msg, num \\ 1) do
		case num <= @max_cycle && SwarmUtil.sync_call(service, msg) do
			:ok ->
				:ok
			{:ok, _} ->
				:ok
			false ->
				Logger.error(inspect({service, msg, " Apply Max Time"}))
				:ok
			server_starting() ->
				Logger.error(inspect({service, " IS Starting"}))
				:timer.apply_after(
					5000,
					__MODULE__,
					:sync_call,
					[service, msg, num]
				)
			err ->
				Logger.error(inspect{service, msg, err})
				:timer.apply_after(
					@rpc_cycle_time,
					__MODULE__,
					:sync_call,
					[service, msg, num + 1]
				)
		end
		:ok
	end

	def rpc_call(node_, m, f, a, num \\ 1) do
		node_ != nil && is_atom(node_) &&
			case num <= @max_cycle && :rpc.call(node_, m, f, a) do
				:ok ->
					:ok
				false ->
					Logger.error(inspect{m, f, a, " Max RpcCall Time"})
					:ok
				err ->
					Logger.error(inspect{node_, m, f, a, "-----------", err})
					:timer.apply_after(
						@rpc_cycle_time,
						__MODULE__,
						:rpc_call,
						[node_, m, f, a, num + 1]
					)
			end
		:ok
	end



end
